<?php

require_once 'Vega/Db/Mysql.php';

class Vega_Db_Mysqli extends Vega_Db_Mysql
{
    protected $_functions = array(
        'fetch_array'   => 'mysqli_fetch_array',
        'query'         => 'mysqli_query',
        'connect'       => 'mysqli_connect',
        // no persistent connect in mysqli
        'pconnect'      => 'mysqli_connect',
        'insert_id'     => 'mysqli_insert_id',
        'select_db'     => 'mysqli_select_db',
        'escape_string' => 'mysqli_escape_string',
        'error'         => 'mysqli_error',
        'num_rows'      => 'mysqli_num_rows',
        'free_result'   => 'mysqli_free_result',
        'affected_rows' => 'mysqli_affected_rows',
    );

    protected $_resultMode = null;

    public function  __construct($masterConfig, $slaveConfig = null) {
        
        parent::__construct($masterConfig, $slaveConfig);
        $this->_resultMode = MYSQLI_STORE_RESULT;
    }
    
    public function escape($string)
    {
        $this->connect('master');
        return mysqli_real_escape_string($string, $this->_conns['master']);
    }

    /**
     * Use unbuffered query
     *
     * @param boolean $use
     */
    public function useUnbufferedQuery($use = true)
    {
        if ($use)
        {
            $this->_resultMode = MYSQLI_USE_RESULT;
        }
        else
        {
            $this->_resultMode = MYSQLI_STORE_RESULT;
        }
        return $this;
    }
    
    /**
     * Select Db
     *
     * @param string $dbName
     * @param resource $connection
     */
    public function selectDb($dbName, $connection)
    {
        $this->_functions['select_db']($connection, $dbName);
    }
    
    
    /**
     * Does a SQL query.
     * This is stand behind all SQL operation funtions
     *
     * @param string $sql
     * @param string $conn
     * @return resource
     */
    protected function _query($sql, $conn)
    {
        $this->connect($conn);
        
        $result = $this->_functions['query']($this->_conns[$conn], $sql, $this->_resultMode);
        
        if (false === $result)
        {
            require_once 'Vega/Db/Exception.php';
            throw new Vega_Db_Exception('SQL error: ' . $this->_functions['error']($this->_conns[$conn]));
        }
        
        return $result;
    }
    
    /**
     * Begins a transaction
     *
     * @return mixed
     */
    public function beginTransaction()
    {
        $this->connect('master');
        return mysqli_autocommit($this->_conns['master'], false);
    }
    
    /**
     * Rolls back a transaction
     *
     * @return mixed
     */
    public function rollBack()
    {
        $this->connect('master');
        return mysqli_rollback($this->_conns['master']);
    }
    
    /**
     * Commits
     *
     * @return mixed
     */
    public function commit()
    {
        $this->connect('master');
        return mysqli_commit($this->_conns['master']);
    }
    
}

